package com.yuncool.auth.handler;

import com.alibaba.fastjson.JSONObject;
import com.yuncool.ServiceResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 未登陆用户处理
 */
@Component
public class LoginAuthenticationEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
		ServiceResult<Boolean> result = new ServiceResult<>();
		result.setResultCode(String.valueOf(HttpStatus.UNAUTHORIZED.value()));
		result.setResultMsg("请登录!");
		result.setResultData(false);
		httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
		httpServletResponse.setContentType("application/json;charset=UTF-8");
		httpServletResponse.getWriter().write(JSONObject.toJSONString(result));
	}

}
